package com.xca.is.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.widget.ViewPager2;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.xca.is.R;
import com.xca.is.adapter.VideosAdapter;
import com.xca.is.dataIntent.FragmentIsDestory;
import com.xca.is.dataIntent.VideoPlayModel;
import com.xca.is.entity.VideoEntity;
import com.xca.is.http.HttpConnect;
import com.xca.is.model.VideoModel;

import java.util.ArrayList;
import java.util.List;

public class VideoFragment extends Fragment implements HttpConnect {
    private ViewPager2 viewPager ;
    private List<Fragment> fragmentList ;
    private VideosAdapter adapter ;

    private List<String> videoUrls ;
    private ViewModelProvider provider ;
    private VideoModel model ;
    private MutableLiveData<VideoEntity> liveData ;

    private RelativeLayout loadings ;
    private FragmentIsDestory fragmentIsDestory ;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_video, container, false);

    }

    public void setData(FragmentIsDestory fragmentIsDestory){
        this.fragmentIsDestory = fragmentIsDestory ;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewPager = view.findViewById(R.id.video_page);
        loadings = view.findViewById(R.id.l_loading);

        loadings.setVisibility(View.GONE);
        // 初始化fragmentList，确保只初始化一次
        if (fragmentList == null) {
            fragmentList = new ArrayList<>();
        }

// 初始化videoUrls和其他ViewModel相关的对象
        videoUrls = new ArrayList<>();
        provider = new ViewModelProvider(this);
        model = provider.get(VideoModel.class);
        model.setData(this);

// 设置LiveData观察者
        liveData = (MutableLiveData<VideoEntity>) model.getLiveData();
        liveData.observe(getViewLifecycleOwner(), videoEntity -> {
            if (videoEntity != null) {
                // 创建新的Video2Fragment实例，并添加到列表中
//                fragmentList.add(new Video2Fragment(this,videoEntity.getVideos().get(0).getVideo_url()));
                fragmentList.add(new Video2Fragment(this,videoEntity.getVideos().get(0).getVideo_url()));


                // 更新适配器，考虑使用notifyItemInserted()代替notifyDataSetChanged()
                int position = fragmentList.size() - 1;
                if (adapter != null) {
                    // 通知适配器有新项目插入
                    adapter.notifyItemInserted(position);
                }
            }
        });

// 创建并设置适配器
        adapter = new VideosAdapter(requireActivity(), getLifecycle(), fragmentList);
        viewPager.setAdapter(adapter);

// 注册ViewPager的页面改变回调
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                Log.d("viewPage监听", String.valueOf(position));
                if (position == fragmentList.size() - 1) {
                    // 尝试获取更多数据前，先检查是否已经有加载中的状态
                        try {
                            model.getData();
                        } catch (Exception e) {
                            // 更具体的异常处理
                            Log.e("TAG", "Error while fetching data", e);
                        }
                }
            }
        });

// 初始加载数据
        model.getData();

    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
            Log.d("VideoFragment页面已不可见", "视频播放页面已不可见");
            fragmentIsDestory.isDestory(true);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        setUserVisibleHint(false);
        Log.d("已更换Fragment", "已更换Fragment");
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
       // Toast.makeText(getContext(), "已销毁Fragment", Toast.LENGTH_SHORT).show();

    }

    @Override
    public void Loading(boolean loading) {
        loadings.setVisibility(loading?View.VISIBLE:View.GONE);
    }

    @Override
    public void Success(Object object) {

    }

    @Override
    public void Fail(String... msg) {

    }

    @Override
    public void Error(String msg) {

    }

    @Override
    public void Complete() {
        loadings.setVisibility(View.GONE);
    }

    @Override
    public void Timeout() {

    }

    @Override
    public void TokenError() {

    }
}